package bmatch.tech.cloud.service.impl;

import bmatch.tech.cloud.dao.FileModelMapper;
import bmatch.tech.cloud.model.FileModel;
import bmatch.tech.cloud.model.Response;
import bmatch.tech.cloud.service.FileService;
import bmatch.tech.cloud.util.IDUtil;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.ws.rs.core.MediaType;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * FileServiceImpl的注释
 *
 * @author: Awake
 * @date: 2018-12-14 14:35
 **/
@Service
public class FileServiceImpl implements FileService {

    /**
     * 日志输出
     */
    Logger log = (Logger) LoggerFactory.getLogger(FileServiceImpl.class);

    private final FileModelMapper mapper;

    @Autowired
    public FileServiceImpl(FileModelMapper mapper) {
        this.mapper = mapper;
    }

    @Override
    public Response upload(String userId, InputStream inputStream, String path, String name) {
        Response response = new Response();
        //检查是否已经存在
        List<FileModel> myFileModels = mapper.select(userId, null, null);
        boolean exist = isExist(myFileModels, true, userId, path, name);
        if (exist) {
            response.setMessage("文件" + path + (path.equals("/") ? " " : "/ ") + name + "已经存在");
            response.setCode(Response.RESPONSE_BAD_REQUEST);
            return response;
        }

        String id = IDUtil.getUUID();
        File file = new File("FilePool/" + id + name.substring(name.lastIndexOf(".")));
        if (file.exists()) {
            file.delete();
        }
        try {
            FileUtils.copyInputStreamToFile(inputStream, file);
        } catch (IOException e) {
            log.error("存到文件失败", e);
            response.setCode(Response.RESPONSE_BAD_REQUEST);
            response.setMessage("文件存储失败");
            return response;
        }

        //新建一个归档
        FileModel f = new FileModel();
        f.setType(true);
        f.setUserId(userId);
        f.setId(IDUtil.getUUID());
        f.setPath(path);
        f.setName(name);
        f.setGmtCreated(new Date());
        f.setStorePath(file.getAbsolutePath());
        //保存到数据库并返回响应
        mapper.insert(f);
        response.setCode(Response.RESPONSE_OK);
        response.setMessage("成功创建一个文件 " + name + " 在目录" + path + "下");
        return response;
    }

    @Override
    public javax.ws.rs.core.Response download(String userId, String path, String name) {
        //查询出是否存在
        List<FileModel> myFileModels = mapper.select(userId, null, null);
        boolean exist = isExist(myFileModels, true, userId, path, name);
        if (!exist) {
            Response resp = new Response();
            resp.setCode(Response.RESPONSE_BAD_REQUEST);
            resp.setMessage("文件" + path + "/  " + name + "不存在");
            return javax.ws.rs.core.Response.ok(resp, MediaType.APPLICATION_JSON).build();
        }
        //取出文件储存路径并返回数据流
        FileModel target = myFileModels.stream().filter((fileModel -> fileModel.getType() == true &&
                fileModel.getPath().equals(path) &&
                fileModel.getName().equals(name))).collect(toList()).get(0);

        File file = new File(target.getStorePath());
        return javax.ws.rs.core.Response
                .ok(file)
                .header("Content-disposition", "attachment;filename=" + target.getName())
                .header("Cache-Control", "no-cache").build();
    }

    @Override
    public Response delete(String userId, String path, String name) {
        Response response = new Response();
        //检查是否已经存在
        List<FileModel> myFileModels = mapper.select(userId, null, null);
        boolean exist = isExist(myFileModels, true, userId, path, name);
        if (!exist) {
            response.setMessage("文件" + path + "/  " + name + "不存在");
            response.setCode(Response.RESPONSE_BAD_REQUEST);
            return response;
        }

        //删除
        FileModel target = myFileModels.stream()
                .filter((fileModel -> fileModel.getType() == true &&
                        fileModel.getPath().equals(path) &&
                        fileModel.getName().equals(name))).collect(toList()).get(0);
        mapper.deleteByPrimaryKey(target.getId());
        response.setMessage("文件" + path + "/  " + name + "已经删除");
        response.setCode(Response.RESPONSE_OK);
        return response;
    }

    @Override
    public Response rename(String userId, String path, String originalName, String targetName) {
        Response response = new Response();
        //检查是否存在
        List<FileModel> myFileModels = mapper.select(userId, null, null);
        boolean exist = isExist(myFileModels, true, userId, path, originalName);
        if (!exist) {
            response.setMessage("文件" + path + "/  " + originalName + "不存在");
            response.setCode(Response.RESPONSE_BAD_REQUEST);
            return response;
        }

        //重新命名
        FileModel target = myFileModels.stream()
                .filter((fileModel -> fileModel.getType() == true &&
                        fileModel.getPath().equals(path) &&
                        fileModel.getName().equals(originalName))).collect(toList()).get(0);
        target.setName(targetName);
        mapper.updateByPrimaryKey(target);
        response.setMessage("文件" + path + "/  " + originalName + "已经重新命名");
        response.setCode(Response.RESPONSE_OK);
        return response;
    }

    @Override
    public Response shift(String userId, String name, String originalPath, String targetPath) {
        Response response = new Response();
        List<FileModel> myFileModels = mapper.select(userId, null, null);

        //检查已经存在 本文件 和 目标文件夹
        boolean oriExist = isExist(myFileModels, true, userId, originalPath, name);

        String tarPath = originalPath.substring(0, originalPath.lastIndexOf("/"));
        String tarName = originalPath.substring(originalPath.lastIndexOf("/") + 1);
        boolean tarExist = isExist(myFileModels, false, userId, tarPath, tarName);

        if (!oriExist) {
            response.setMessage("文件" + originalPath + "/  " + name + "不存在");
            response.setCode(Response.RESPONSE_BAD_REQUEST);
            return response;
        }

        if (!tarExist) {
            response.setMessage("目标文件夹" + originalPath + "不存在");
            response.setCode(Response.RESPONSE_BAD_REQUEST);
            return response;
        }

        //将本文件夹的路径修改成目标文件夹的全路径
        FileModel target = myFileModels.stream().filter((fileModel -> fileModel.getType() == true &&
                fileModel.getPath().equals(originalPath) &&
                fileModel.getName().equals(name))).collect(toList()).get(0);
        target.setPath(targetPath);
        mapper.updateByPrimaryKey(target);
        response.setMessage("文件" + originalPath + "/  " + name + "已经转移到:" + targetPath + "下");
        response.setCode(Response.RESPONSE_OK);
        return response;
    }

    public boolean isExist(List<FileModel> fileModels, boolean type, String userId, String path, String name) {
        return fileModels.stream()
                .anyMatch(fileModel -> fileModel.getType() == type &&
                        fileModel.getPath().equals(path) &&
                        fileModel.getName().equals(name));
    }
}
